package cn.golxen.blog.commons.utils;

import cn.golxen.blog.exception.exceptionClass.GetTokenException;
import io.jsonwebtoken.*;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class JWTUtils {

    static final String secret="Golxen666";

    public static String createJwtToken(String id){

        Date date = LocalDateTimeUtils.toDate();
        Calendar cal=new GregorianCalendar();
        cal.setTime(date);
        cal.add(Calendar.HOUR_OF_DAY,24);
        Date expireDate=cal.getTime();

        String token= Jwts.builder()
                .setHeaderParam("typ","JWT")
                .setIssuer("Golxen")
                .setSubject(id)
                .setIssuedAt(date)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();

        return token;
    }

    public static boolean isExpires(String token){
        Claims claims= Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
//        System.out.println(claims.getExpiration());
        return LocalDateTimeUtils.toDate().getTime()>claims.getExpiration().getTime();
    }

    public static boolean verifyJWT(String token){
        try {
            Claims claims= Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        }catch (Exception e){
            e.printStackTrace();
            throw new GetTokenException();
        }
        return true;

    }
}
